import React from 'react'
import { InputList, IconFont, SelectList, Input, Modal, Checkbox, Link, TitleBar } from '../../ui-components'
import { connect } from 'react-redux'
import util from '../../util'
import style from './style.relationManage'
import cx from 'classnames'
import { presets, StaggeredMotion, Motion, spring } from 'react-motion'

const ROOT_TEAM = '2b1e6d025ac28868'

function ToolTip(props){
    return(
        <a href="javascript:void(0);" className={style["toolTip"]}>
            <span className={style["toolTip-content"]}>{props.title}</span>
            {
                props.children
            }
        </a>
    );
}

export default
@connect(({ app, team }) => ({ app, team }))
class RelationManage extends React.Component {

  init = true

  initState = {
    editAll: false,
    ajustReportee: {},
    ajustDialog: false,
    reportees: [],
    selectedReportor: {},
    searchReportor: '',
    clicked: {}
  }

  state = this.initState

  componentWillUnmount() {
    this.props.clearTeamReportees()
  }

  componentWillReceiveProps(props) {
    if (props.team.updateReportees && !this.props.team.updateReportees) {
      this.props.reloadReportees(ROOT_TEAM)
    }
  }

  changeReportor() {
    const { editAll, reportees, searchReportor, selectedReportor } = this.state
    if (!(!util.isNull(searchReportor) && searchReportor == selectedReportor.fullName)) return

    const callback = () => {
      this.setState({
        ...this.initState
      })
    }

    if (editAll) {
      this.props.updateReportees({
        reportor: selectedReportor.userId,
        reportees: reportees.map(obj => ({idValue: obj.idValue}))
      }, callback)

      this.setState({
        reportees: [],
        editAll: false
      })

    } else {
      this.props.updateReportees({
        reportor: selectedReportor.userId,
        reportees: [ { idValue: this.state.ajustReportee.userId } ]
      }, callback)
    }

    this.resetAjustDialog()

    util.dialog.call(this, 'ajustDialog')
  }

  handleSelectReportor(item) {
    this.setState({
      selectedReportor: item,
      searchReportor: item.fullName
    })
    this.props.clearAtList()
  }

  searchReportor(e) {
    this.setState({
      searchReportor: e.target.value
    })

    if (util.isNull(e.target.value)) return
    this.fetchAtList(e.target.value)
  }
  fetchAtList(value){
    this.props.fetchAtList({
      keyword: value,
      type: 5,
    })
  }
  handleCheck(e, { userId }, leader) {
    e.stopPropagation()

    const cur = this.state.reportees.some(obj => obj.idValue == userId)

    if (cur) {
      this.setState({
        reportees: this.state.reportees.filter(obj => obj.idValue != userId)
      })
    } else {
      this.setState({
        reportees: [
          ...this.state.reportees
            .filter(obj => {
              // 取消leader勾选
              if (obj.idValue == leader) return false
              return true
            })
            .filter(obj => {
              // 取消手下的勾选
              if (obj.leader == userId) return false
              return true
            }),
          {
            idValue: userId,
            leader
          }
        ]
      })
    }
  }

  closeAjustDialog() {
    this.props.clearAtList()
    util.dialog.call(this, 'ajustDialog')
  }

  componentDidMount() {
    this.props.fetchReportees(ROOT_TEAM)
  }

  handleAjustReportee(e, reportee) {
    e.stopPropagation()
    this.resetAjustDialog()
    this.setState({
      ajustReportee: reportee
    })
    util.dialog.call(this, 'ajustDialog')
  }

  handleAjustReporteeAll() {
    util.dialog.call(this, 'ajustDialog')
  }

  resetAjustDialog() {
    this.setState({
      searchReportor: '',
      selectedReportor: {},
      ajustReportee: {}
    })
  }

  renderReportees(teamReportees) {
    if (!teamReportees.length) return null

    teamReportees = util.deepClone(teamReportees)

    for(var i=0;i<teamReportees.length;i++) {
      for(var j=1;j<teamReportees.length;j++) {
        for(var k=0;k<teamReportees[i].reportees.length;k++) {
          if (teamReportees[j].leader == teamReportees[i].reportees[k].userId) {
            teamReportees[i].reportees[k].reportee = teamReportees[j]
          }
        }
      }
    }

    function render(reportees, leader) {
      //if (!reportees.length) return null
      return (
        <Motion defaultStyle={{ opacity: 0 }} style={{
          opacity: spring(reportees.length? 1: 0)
        }}>
          {
            ({ opacity }) => {
              return (
                <ul style={{ opacity }}>
                  {
                    reportees.map((reportee, i) => (
                      <li 
                        ref={el => {
                          if (el) {
                            if (this.init) {
                              this.props.fetchReportees(reportee.userId)
                              this.setState({
                                clicked: {
                                  ...this.state.clicked,
                                  [reportee.userId]: !this.state.clicked[reportee.userId]
                                }
                              })
                              this.init = false
                            }
                          }
                        }}
                        className={cx({
                          [style.editAll]: this.state.editAll,
                          [style.reportee]: true,
                          [style.clicked]: this.state.clicked[reportee.userId],
                          [style['has-reportee']]: reportee.hasReportee
                        })}
                        key={i}
                      >
                        <span 
                          onClick={() => {
                            this.init = false
                            if (reportee.reportee) {
                              this.props.clearReportees(reportee.userId)
                            }
                            else {
                              this.props.fetchReportees(reportee.userId)
                            }
                            this.setState({
                              clicked: {
                                ...this.state.clicked,
                                [reportee.userId]: !this.state.clicked[reportee.userId]
                              }
                            })
                          }}
                        >
                          {
                            this.state.editAll?
                            <Checkbox 
                              active={this.state.reportees.some(obj => obj.idValue == reportee.userId)}
                              onClick={e => this.handleCheck(e, reportee, leader)} 
                              className={style.check}
                            />
                            : null
                          }
                            <IconFont value="arrow"/>
                            <Link
                              className={style.avatar}
                              src={reportee.avatarUrl}
                              srcIcon="avatar"
                              width="26"
                              noHover
                            />

                            <span> <ToolTip title={reportee.emailAddress}>{ reportee.fullName }</ToolTip></span>
                          <span>{ reportee.jobTitleName? <span className={style['job-title']}>{reportee.jobTitleName}</span>: null }</span>
                          <Link 
                            icon="edit_profile"
                            target="_blank"
                            className={style.userHome} 
                            to={`#/hr/team-memeber-edit/${reportee.userId}`}
                          />
                          <Link
                            onClick={e => this.handleAjustReportee(e, reportee)} 
                            className={style.ajust}>修改</Link>

                        </span>
                        {
                          render.call(this, reportee.reportee? reportee.reportee.reportees: [], reportee.reportee? reportee.reportee.leader: null)
                        }
                      </li>
                    ))
                  }
                </ul>
              )
            }
          }
        </Motion>
      )
    }

    return render.call(this, teamReportees[0].reportees, teamReportees[0].leader)
  }

  handleEditAll() {
    this.setState({
      editAll: !this.state.editAll
    })
  }

  requestAjust() {}

  render() {
    const { teamReportees } = this.props.team
    let actions = [
      {
        blueLine: true,
        label: this.state.editAll? '退出批量操作': '批量操作',
        handler: () => this.handleEditAll()
      }
    ]
    if (this.state.editAll) {
      actions = [
        actions[0],
        {
          disabled: !this.state.reportees.length,
          label: '调整汇报关系',
          handler: ::this.handleAjustReporteeAll
        },
      ]
    }
    return (
      <div>
        <TitleBar 
          fixed
          actions={actions}
          label="汇报关系管理"/>
        <div className={style.teamReportees}>
          { this.renderReportees(teamReportees) }
        </div>
        <Modal
          active={this.state.ajustDialog}
          onRequestClose={::this.closeAjustDialog}
          actions={[
            'cancel',
            ::this.changeReportor
          ]}
          title={`更改${this.state.ajustReportee.fullName || ''}的汇报对象`}
        >
          <div>
            <InputList
              autoFocus
              clear={this.props.clearAtList}
              fetch={::this.fetchAtList}
              onSelect={::this.handleSelectReportor}
              list={this.props.app.atList}
              placeholder="输入汇报对象姓名..."
            />
          </div>
        </Modal>
      </div>
    )
  }
}
